import React, { Component } from 'react';
import {UserAPI} from '../utils';
import {Prompt} from '../react-router';
export default class UserAdd extends Component {
  usernameRef

  state = {isBlocking:false}

  constructor(props) {
    super(props);
    this.usernameRef = React.createRef();
  }
  handleSubmit = (event) => {
    event.preventDefault();

    this.setState({
      isBlocking: false
    }, /*等价于在componentDidUpdate里执行→*/() => {
      const username = this.usernameRef.current.value;
      UserAPI.add({id: Date.now() + '', username});
      this.props.history.push('/user/list');
    });
  }
  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <Prompt
          when={this.state.isBlocking}
          message = {
            (location/*createBrowserRouter里调用该方法时 会将location对象传进来*/)=>`请问你确定要跳转到${location.pathname}吗?`
          }
        />
        <input  type="text" ref={this.usernameRef}  onChange={(event) => {
          this.setState({ isBlocking: event.target.value.length > 0 });
        }} />
      </form>
    )
  }
}
